import 'package:get/get.dart';
import 'package:get/get_connect/http/src/request/request.dart';

Future<Map<String, String>> beforeLoginHeader() async {
  Map<String, String> headers = {};

  return headers;
}

Future<Map<String, String>> afterLoginHeader() async {
  Map<String, String> headers = {};
  return headers;
}

enum HttpMethodEnum { POST, GET, PATCH, DELETE, PUT }

enum HeaderType {
  beforeLogin(getHeaderFunction: beforeLoginHeader),
  noHeader(),
  afterLogin(getHeaderFunction: afterLoginHeader);

  final Future<Map<String, String>> Function()? getHeaderFunction;

  const HeaderType({this.getHeaderFunction});
}

var reqInterceptor = (Request<dynamic> request) async {
  return request;
};

var resInterceptor =
    (Request<dynamic> request, Response<dynamic> response) async {
      print("emmmmm:${response.statusCode}");

      return response;
    };

class HttpApiService extends GetConnect {
  HttpApiService._();

  static final HttpApiService instance = HttpApiService._();

  @override
  void onInit() {
    httpClient.timeout = const Duration(minutes: 1);
    httpClient.addRequestModifier(reqInterceptor);
    httpClient.addResponseModifier(resInterceptor);
  }
}

class HttpApi {
  final String path;
  final HttpMethodEnum method;
  final String baseUrl;
  final Future<String> Function()? urlParamGen;
  HeaderType headerType;

  HttpApi({
    required this.path,
    required this.method,
    required this.baseUrl,
    this.urlParamGen,
    required this.headerType,
  });

  HttpApi setHeaderType(HeaderType type) {
    headerType = type;
    return this;
  }

  Future<Response<T>> request<T>({
    dynamic body,
    Map<String, String>? headers,
    Decoder<T>? decoder,
    String? moreParam,
    String? contentType,
  }) async {
    final fullUrl =
        "$baseUrl${await urlParamGen?.call() ?? ""}$path${moreParam ?? ""}";
    if (headerType.getHeaderFunction != null) {
      headers ??= {};
      headers.addAll(await headerType.getHeaderFunction!.call());
    }

    return await HttpApiService.instance.request<T>(
      fullUrl,
      method.name,
      body: body,
      headers: headers,
      decoder: decoder,
      contentType: contentType,
    );
  }
}

mixin HttpApiModule {
  String get baseUrl;

  HttpApi api({
    required String path,
    required HttpMethodEnum method,
    Future<String> Function()? urlParamGen,
    HeaderType headerType = HeaderType.noHeader,
  }) {
    return HttpApi(
      path: path,
      method: method,
      baseUrl: baseUrl,
      headerType: headerType,
      urlParamGen: urlParamGen,
    );
  }
}
